#!/usr/bin/env python3
"""
文本比较脚本
用于比较两个文本文件的差异
"""

import sys
import argparse

def read_file_lines(filename):
    """读取文件并返回行列表"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return [line.rstrip('\n\r') for line in file]
    except FileNotFoundError:
        print(f"错误：文件 '{filename}' 不存在")
        sys.exit(1)
    except Exception as e:
        print(f"读取文件 '{filename}' 时出错：{e}")
        sys.exit(1)

def compare_files(file1, file2):
    """比较两个文件的内容"""
    lines1 = read_file_lines(file1)
    lines2 = read_file_lines(file2)
    
    # 使用集合来快速查找差异
    set1 = set(lines1)
    set2 = set(lines2)
    
    # 找出只在file1中存在的行
    only_in_file1 = set1 - set2
    # 找出只在file2中存在的行
    only_in_file2 = set2 - set1
    
    return only_in_file1, only_in_file2

def compare_files_with_order(file1, file2):
    """比较两个文件的内容（保持原始顺序）"""
    lines1 = read_file_lines(file1)
    lines2 = read_file_lines(file2)
    
    set2 = set(lines2)
    set1 = set(lines1)
    
    # 保持原始文件中的顺序
    only_in_file1 = [line for line in lines1 if line not in set2]
    only_in_file2 = [line for line in lines2 if line not in set1]
    
    return only_in_file1, only_in_file2

def main():
    parser = argparse.ArgumentParser(description='比较两个文本文件的差异')
    parser.add_argument('file1', help='第一个文本文件')
    parser.add_argument('file2', help='第二个文本文件')
    parser.add_argument('-o', '--ordered', action='store_true', 
                       help='保持原始文件中的行顺序')
    
    args = parser.parse_args()
    
    if args.ordered:
        only_in_a, only_in_b = compare_files_with_order(args.file1, args.file2)
    else:
        only_in_a, only_in_b = compare_files(args.file1, args.file2)
    
    # 输出结果
    print("=" * 50)
    print(f"比较结果：{args.file1} vs {args.file2}")
    print("=" * 50)
    
    print(f"\n在 {args.file1} 中独有（不在 {args.file2} 中）的行：")
    print("-" * 30)
    if only_in_a:
        for i, line in enumerate(only_in_a, 1):
            print(f"{i:3d}: {line}")
    else:
        print("（无）")
    
    print(f"\n在 {args.file2} 中独有（不在 {args.file1} 中）的行：")
    print("-" * 30)
    if only_in_b:
        for i, line in enumerate(only_in_b, 1):
            print(f"{i:3d}: {line}")
    else:
        print("（无）")
    
    # 统计信息
    print("\n" + "=" * 50)
    print("统计信息：")
    print(f"在 {args.file1} 中独有的行数：{len(only_in_a)}")
    print(f"在 {args.file2} 中独有的行数：{len(only_in_b)}")
    print("=" * 50)

if __name__ == "__main__":
    main()